import re
import requests

def get_bilibili_cover_url(bilibili_url):
    match = re.search(r'BV[0-9A-Za-z]+', bilibili_url)
    if not match:
        return ''
    bvid = match.group(0)
    api_url = f'https://api.bilibili.com/x/web-interface/view?bvid={bvid}'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
    }
    try:
        resp = requests.get(api_url, timeout=5, proxies={}, headers=headers)
        if resp.status_code == 200 and resp.text.strip():
            data = resp.json()
            if data.get('code') == 0:
                # 优先用pic字段
                if data['data'].get('pic'):
                    return data['data']['pic']
                # 其次尝试pages[0].first_frame
                pages = data['data'].get('pages', [])
                if pages and pages[0].get('first_frame'):
                    return pages[0]['first_frame']
    except Exception as e:
        print(f'获取B站封面失败: {e}')
    return ''
